package tv.danmaku.ijk.app.activity;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import java.util.ArrayList;
import java.util.List;

import tv.danmaku.ijk.app.wdget.ControlPlayView;
import tv.danmaku.ijk.app.wdget.MyPlayer;
import tv.danmaku.ijk.media.player.R;

public class LiveServiceActivity extends AppCompatActivity {

    private MyPlayer myPlayer;
    private LinearLayout rootLayout;
    private DisplayMetrics metrics;

    private LinearLayout chatLayout;

    private RecyclerView r_ChatList;
    private ChatAdapter chatAdapter;

    private EditText inputText;
    private Button sendButton;

    private boolean isLandscape = true;

    private void initView () {

        rootLayout = findViewById(R.id.linearLayout_LiveService);
        metrics = getResources().getDisplayMetrics();

        chatLayout = findViewById(R.id.linearLayout_ChatLayout);

        myPlayer = new MyPlayer(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int) (metrics.density * 250));
        params.bottomMargin = 0;
        myPlayer.setLayoutParams(params);
        myPlayer.setViewControllerListener(viewControllerListener);
        rootLayout.addView(myPlayer, 0);

        r_ChatList = findViewById(R.id.recyclerView_ChatList);
        r_ChatList.setLayoutManager(new LinearLayoutManager(this));
        chatAdapter = new ChatAdapter();
        r_ChatList.setAdapter(chatAdapter);

        inputText = findViewById(R.id.editText_InputMessage);

        sendButton = findViewById(R.id.button_InputMessage);
        sendButton.setOnClickListener(onClickListener);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    private void changeScreenDirection () {
        View decorView = getWindow().getDecorView();
        int option = 0;
        if (isLandscape) {
            chatLayout.setVisibility(View.VISIBLE);
            option = View.SYSTEM_UI_FLAG_VISIBLE;
            decorView.setSystemUiVisibility(option);
        } else {
            option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(option);
        }
        new Thread(){
            @Override
            public void run () {
                super.run();
                try {
                    sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.sendEmptyMessage(0x10012);
            }
        }.start();
    }

    // 延时刷新布局 解决低端机型因为状态栏高度发生的计算错误问题
    private void reLayoutScreen(){
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) myPlayer.getLayoutParams();
        if (isLandscape) {
            params.height = (int) (metrics.density * 250);
            chatLayout.getLayoutParams().height = metrics.heightPixels -(int) (metrics.density * 250) - getStatusBarHeight();
        } else {
            params.height = metrics.widthPixels;
        }
        myPlayer.setLayoutParams(params);
    }

    private int getStatusBarHeight() {
        Resources resources = getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen","android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }
    private void initInfoView () {
//        myPlayer.setUrl("rtmp://167.179.90.179/live/myvideo");
//      myPlayer.setUrl("rtmp://167.179.90.179/live/test");
      myPlayer.setUrl("rtmp://192.168.31.209/live/test");

    }

    @Override
    protected void onCreate (@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_liveservice);
        initView();

        initInfo();

        initInfoView();
    }

    @Override
    protected void onResume () {
        super.onResume();
        myPlayer.start();
    }

    @Override
    protected void onPause () {
        super.onPause();
        myPlayer.pause();
    }

    @Override
    protected void onStop () {
        super.onStop();
        myPlayer.stop();
    }

    @Override
    protected void onDestroy () {
        super.onDestroy();

    }

    @Override
    public void onConfigurationChanged (@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == 1) {//竖屏
            isLandscape = true;
        } else { // 横屏
            isLandscape = false;
        }
        changeScreenDirection();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick (View v) {
            if(v.getId() == R.id.button_InputMessage){
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                View ve = getWindow().peekDecorView();
                if (null != ve) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }

                ChatItem item = new ChatItem();
                item.name = "用户3";
                item.msg = inputText.getText().toString();
                chats.add(item);
                inputText.setText("");

                chatAdapter.notifyDataSetChanged();
            }
        }
    };

    private Handler handler = new Handler(){
        @Override
        public void handleMessage (@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0x10012:
                    reLayoutScreen();
                    break;
            }
        }
    };

    private ControlPlayView.ViewControllerListener viewControllerListener = new ControlPlayView.ViewControllerListener() {
        @Override
        public void optionLayoutChange () {
            changeScreenDirection();
        }

        @Override
        public void onBack () {
            // 关闭界面
            finish();
        }

        @Override
        public void onZoom () {
            if (isLandscape) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
            }
        }
    };


    private List<ChatItem> chats = new ArrayList<>();

    private void initInfo () {
        ChatItem item = new ChatItem();
        item.name = "用户1";
        item.msg = "开始游戏了";
        chats.add(item);

        item = new ChatItem();
        item.name = "赵四";
        item.msg = "别着急";
        chats.add(item);

        item = new ChatItem();
        item.name = "用户4";
        item.msg = "1";
        chats.add(item);
    }

    //=====================================================================
    //  消息适配器
    //=====================================================================

    public class ChatItem {
        private String name;
        private String msg;

        public String getName () {
            return name;
        }

        public void setName (String name) {
            this.name = name;
        }

        public String getMsg () {
            return msg;
        }

        public void setMsg (String msg) {
            this.msg = msg;
        }
    }

    private class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHoulder> {

        @NonNull
        @Override
        public ChatViewHoulder onCreateViewHolder (@NonNull ViewGroup parent, int viewType) {
            ViewGroup view = (ViewGroup) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat, parent, false);
            return new ChatViewHoulder(view);
        }

        @Override
        public void onBindViewHolder (@NonNull ChatViewHoulder holder, int position) {
            ChatItem item = chats.get(position);
            holder.name.setText(item.getName());
            holder.msg.setText(item.getMsg());
        }

        @Override
        public int getItemCount () {
            return chats.size();
        }

        public class ChatViewHoulder extends RecyclerView.ViewHolder {
            TextView name;
            TextView msg;

            public ChatViewHoulder (@NonNull View itemView) {
                super(itemView);
                name = itemView.findViewById(R.id.textView_Item_Message_Name);
                msg = itemView.findViewById(R.id.textView_Item_Message_Msg);
            }
        }

    }


}
